const { link_category, links } = require('@/model');

class LinkCategoryService {
  async getCategories(params) {
    const res = await link_category.findAndCountAll({
      order: [['order', 'ASC']]
    });
    return {
      total: res.count,
      list: res.rows.map(row => row.toJSON())
    };
  }

  async getAll() {
    const res = await link_category.findAll({
      order: [['order', 'ASC']],
      include: [
        { model: links, as: 'links', order: [['order', 'ASC']] }
      ]
    });
    return res.map(row => row.toJSON());
  }

  async saveCategory(data) {
    console.log('saveCategory保存分类',data);
    const [category] = await link_category.upsert(data);
    return category;
  }

  async deleteCategory(id) {
    // 删除分类前，先删除该分类下的所有链接
    await links.destroy({ where: { category_id: id } });
    // 删除分类
    const rows = await link_category.destroy({ where: { id } });
    return rows > 0;
  }
}

module.exports = new LinkCategoryService();